package com.alogic.validator.impl.pwd;

import com.alogic.validator.impl.Similar;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.collections4.SetUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.HashSet;
import java.util.Set;

/**
 * 根据SorensenDice指数判断相似性
 *
 * @since 1.6.13.28 [20201218 duanyy] <br>
 */
public class SorensenDice extends Similar {
    protected double threshold = 0.5f;

    @Override
    public void configure(Properties p) {
        super.configure(p);
        threshold = PropertiesConstants.getDouble(p,"threshold",0.5f,true);
    }

    @Override
    protected boolean isSimilar(String key, String value) {
        return sorensenDice(key,value) > threshold;
    }

    public static float sorensenDice(String a, String b) {
        if (StringUtils.isEmpty(a) && StringUtils.isEmpty(b)) {
            return 1f;
        }
        if (StringUtils.isEmpty(a) && StringUtils.isEmpty(b)) {
            return 0f;
        }
        Set<Character> aChar = chars(a);
        Set<Character> bChar = chars(b);
        int intersect = SetUtils.intersection(aChar, bChar).size();
        if (intersect == 0) return 0f;
        int aSize = aChar.size();
        int bSize = bChar.size();
        return (2 * (float) intersect) / ((float) (aSize + bSize));
    }

    public static Set<Character> chars(String str){
        Set<Character> chars = new HashSet<Character>();
        for (int i = 0 ; i < str.length() ; i ++){
            chars.add(str.charAt(i));
        }
        return chars;
    }
}